import axios from 'axios'
import qs from 'qs'
import {
  getToken
} from './local.js'

// Creating an instance
const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
  transformRequest: function(data) {
    return qs.stringify(data); // 请求参数做统一处理
  },
})

//请求拦截
request.interceptors.request.use(config => {
  config.headers.Authorization = getToken();
  return config;
})

//响应拦截
request.interceptors.response.use(response => {
  return response
}, error => {
  let errMsg = '';
  if (error && error.response && error.response.status) {
    switch (error.response.status) {
      case 401:
        errMsg = '登录状态失效，请重新登录';
        break;
      case 402:
        errMsg = '登录信息验证失败，还未登录';
        break;
      case 403:
        errMsg = '拒绝访问';
        break;
      case 404:
        errMsg = '请求资源不存在';
        break;
      case 408:
        errMsg = '请求超时';
        break;
      case 500:
        errMsg = '服务器内部错误';
        break;
      case 501:
        errMsg = '服务未实现';
        break;
      case 502:
        errMsg = '网关错误';
        break;
      case 503:
        errMsg = '服务不可用';
        break;
      case 504:
        errMsg = '网关超时';
        break;
      case 505:
        errMsg = 'HTTP版本不受支持';
        break;
      default:
        errMsg = error.response.data.msg;
    }
  } else {
    errMsg = error;
  }
})

// GET请求
export const get = (url, params = {}) => {
  return request({
    url: url,
    method: 'GET',
    params: params
  })
}
// POST请求
export const post = (url, params = {}) => {
  return request({
    url: url,
    method: 'POST',
    data: params
  })
}
// PUT请求
export const put = (url, params = {}) => {
  return request({
    url: url,
    method: 'PUT',
    data: params
  })
}
//DELETE请求
export const del = (url, params = {}) => {
  return request({
    url: url,
    method: "DELETE",
    data: params
  });
}
